package com.wchen.gdoc.generate.util;

import com.alibaba.fastjson.JSONObject;
import com.wchen.gdoc.generate.config.ApplicationConfigProvide;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;

/**
 * freemarker模板处理器
 *
 * @author  wchen
 * @date    2019/11/8
 */
public class FreemarkerTemplateUtil {


    /**
     * 生成模板内容
     *
     * @param paramsData
     * @param fileName
     * @return
     */
    public static String generateContent(JSONObject paramsData, String fileName) {
        Writer stringWriter = new StringWriter();
        String templateContent = "";
        try {
            // 代码模板配置
            Configuration cfg = ApplicationConfigProvide.getApplicationConfig().getFreemarkerConfiguration();
            Template template = cfg.getTemplate(fileName);
            // 创建一个Writer对象，指定生成的文件保存的路径及文件名
            template.process(paramsData, stringWriter);
            templateContent = stringWriter.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("FreemarkerTemplateUtil generateContent error");
        } finally {
            try {
                stringWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return templateContent;
    }


}